package com.hyk.controller;

import com.hyk.config.SecurityConfig;
import com.hyk.entity.User;
import com.hyk.enums.ApiEnum;
import com.hyk.exception.GlobalException;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

public class BaseController {

    public static User getUser(HttpServletRequest request){
        User user = (User) request.getAttribute("user_token");
        if (user == null){
            Map<String,Object> principal = (Map<String, Object>) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (principal == null){
                throw new GlobalException(ApiEnum.USER_NOT_LOGIN);
            }
            try {
                BeanUtils.populate(user, principal);
            }catch (IllegalAccessException | InvocationTargetException e){
                e.printStackTrace();
            }
            return user;
        }
        return user;
    }

}
